/*
  Copyright 1996-2003
  Simon Whiteside

*/
package simkin.examples.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import simkin.*;

/**
 * This example shows how Simkin can be used within a Java servlet
 * The servlet executes Simkin script contained within a POST request, and returns the 
 * output of the script to the calling browser
 */

public class SimkinServlet extends HttpServlet{
    /**
     * This class channels trace output to the servlet's output stream
     */
    class ServletTracer implements TraceCallback{
	PrintWriter m_Out;
	/** Construct a tracer, which will write to the given writer
	 */
	ServletTracer(PrintWriter out){
	    m_Out=out;
	}
	public void trace(String msg){
	    m_Out.write(msg);
	}
	public void trace(Exception e){
	    e.printStackTrace(m_Out);
	}
    }
    /**
     * Handle a post request - loads the Simkin script from the "code" variable, executes it, and returns the output
     */
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
	String code=req.getParameter("code");
	// Create an interpreter and a context
	Interpreter interpreter=new Interpreter();
	interpreter.setTraceCallback(new ServletTracer(res.getWriter()));
	ExecutableContext ctxt=new ExecutableContext(interpreter);
	try{

	    // Load the treenode
	    TreeNode node=TreeNode.read(new StringReader(code));

	    // Create an executable wrapper
	    TreeNodeObject obj=new TreeNodeObject("Web",node);

	    // call the main method
	    obj.method("main",null,ctxt);
	}catch(Exception e){
	    e.printStackTrace(res.getWriter());
	}
    }  
}
